﻿/* Copyright (C) 2008 - 2011 by John Cronin
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:

 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.

 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */

using System;
using System.Collections.Generic;
using System.Text;

namespace tysos
{
    class PageFault
    {
        internal static bool unwinding = false;

        [ABI.ISR]
        [ABI.AlwaysCompile]
        [ABI.MethodAlias("__pfault")]
        public static void PFHandler(ulong error_code)
        {
            ulong fault_address = ABI.OtherOperations.ReadCR2();

            if (unwinding)
                ABI.OtherOperations.Halt();     // If we are in the middle of unwinding a previous page fault then 
                                                //  any new fault is caught when we reach the end of the stack, so we
                                                //  should stop.

            if (Program.arch.VirtualRegions.heap.contains(fault_address))
            {
                Program.arch.VirtMem.map_page(fault_address);
            }
            else
            {
                /* Check if it something we can allocate, i.e. stack space or SSE storage space or cpu-specific space */
                Virtual_Regions.Region cur_reg = Program.arch.VirtualRegions.list_start;
                while (cur_reg != null)
                {
                    if (cur_reg.contains(fault_address))
                    {
                        if ((cur_reg.type == Virtual_Regions.Region.RegionType.SSE_state) ||
                            (cur_reg.type == Virtual_Regions.Region.RegionType.CPU_specific) ||
                            (cur_reg.type == Virtual_Regions.Region.RegionType.IPC))
                        {
                            Program.arch.VirtMem.map_page(fault_address);
                            return;
                        }
                        else if (cur_reg.type == Virtual_Regions.Region.RegionType.Stack)
                        {
                            /* Check for stack overflow into the guard page */
                            if (fault_address < (cur_reg.start + cur_reg.stack_protect))
                            {
                                Formatter.Write("Page fault.  Address: 0x", Program.arch.BootInfoOutput);
                                Formatter.Write(fault_address, "X", Program.arch.BootInfoOutput);
                                Formatter.WriteLine(Program.arch.BootInfoOutput);
                                Formatter.WriteLine("Stack overflow!", Program.arch.BootInfoOutput);
                                ABI.OtherOperations.Halt();
                            }
                            else
                            {
                                Program.arch.VirtMem.map_page(fault_address);
                                return;
                            }
                        }
                    }

                    cur_reg = cur_reg.next;
                }

                Formatter.Write("Page fault.  Address: 0x", Program.arch.BootInfoOutput);
                Formatter.Write(fault_address, "X", Program.arch.BootInfoOutput);
                Formatter.WriteLine(Program.arch.BootInfoOutput);
                Formatter.WriteLine("Address not allowed!", Program.arch.BootInfoOutput);

                Formatter.Write("Page fault.  Address: 0x", Program.arch.DebugOutput);
                Formatter.Write(fault_address, "X", Program.arch.DebugOutput);
                Formatter.WriteLine(Program.arch.DebugOutput);
                Formatter.WriteLine("Address not allowed!", Program.arch.DebugOutput);

                Program.arch.VirtualRegions.Dump(Program.arch.DebugOutput);

                /* Unwind the stack */
                Unwind u = new Unwind();
                Formatter.WriteLine("Stack trace: ", Program.arch.DebugOutput);

                DumpIP(u.UnwindOneWithErrorCode());
                while (true)
                    DumpIP(u.UnwindOne());

                ABI.OtherOperations.Halt();
            }
        }

        internal static void DumpIP(ulong rip)
        {
            string sym_name = "Unknown";
            ulong offset = rip;

            if (Program.stab != null)
                sym_name = Program.stab.GetSymbolAndOffset(rip, out offset);

            Formatter.Write(sym_name, Program.arch.DebugOutput);
            Formatter.Write(" + ", Program.arch.DebugOutput);
            Formatter.Write(offset, "X", Program.arch.DebugOutput);
            Formatter.WriteLine(Program.arch.DebugOutput);

            Formatter.Write(sym_name, Program.arch.BootInfoOutput);
            Formatter.Write(" + ", Program.arch.BootInfoOutput);
            Formatter.Write(offset, "X", Program.arch.BootInfoOutput);
            Formatter.WriteLine(Program.arch.BootInfoOutput);
        }
    }
}
